package com.hhw.mocklocationsample;

import android.annotation.SuppressLint;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import java.lang.reflect.Method;

public class MockLocationUtils {

    /**
     * 需要系统权限才能正常反射调用
     * 设置模拟定位数据的APP
     * @param mockPackageName
     */
    private static void setMockLocationAPP(Context ct, String mockPackageName) {
        try {
            AppOpsManager appsOpsManager = (AppOpsManager) ct
                    .getSystemService(Context.APP_OPS_SERVICE);

            @SuppressLint("WrongConstant") final ApplicationInfo ai = ct.getPackageManager()
                    .getApplicationInfo(mockPackageName,
                            PackageManager.GET_DISABLED_COMPONENTS);
            Class c = Class.forName("android.app.AppOpsManager");

            Class[] args = new Class[4];
            args[0] = int.class;
            args[1] = int.class;
            args[2] = String.class;
            args[3] = int.class;

            Method setMode = c.getMethod("setMode", args);
            Object[] params = new Object[4];
            params[0] = Integer.valueOf(58);
            params[1] = Integer.valueOf(ai.uid);
            params[2] = new String(mockPackageName);
            params[3] = Integer.valueOf(AppOpsManager.MODE_ALLOWED);
            setMode.invoke(appsOpsManager, params);

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }

    }
}
